package cn.exrick.xboot.modules.Information.controller;

import cn.exrick.xboot.common.utils.HibernateProxyTypeAdapter;
import cn.exrick.xboot.common.utils.PageUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.Information.entity.RealGps;
import cn.exrick.xboot.modules.Information.entity.RealPatrolId;
import cn.exrick.xboot.modules.Information.entity.RiverTourHistory;
import cn.exrick.xboot.modules.Information.service.IRiverTourHistoryService;
import cn.exrick.xboot.modules.webSocket.MyHandler;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.TextMessage;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author lijian
 */
@Slf4j
@RestController
@Api(description = "巡河历史表管理接口")
@RequestMapping("/xboot/riverTourHistory")
@Transactional
public class RiverTourHistoryController {

    @Autowired
    private IRiverTourHistoryService iRiverTourHistoryService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Autowired
    MyHandler myHandler;

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "通过id获取")
    public Result<RiverTourHistory> get(@PathVariable Long id){

        RiverTourHistory riverTourHistory = iRiverTourHistoryService.getById(id);
        return new ResultUtil<RiverTourHistory>().setData(riverTourHistory);
    }

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ApiOperation(value = "获取全部数据")
    public Result<List<RiverTourHistory>> getAll(){

        List<RiverTourHistory> list = iRiverTourHistoryService.list();
        return new ResultUtil<List<RiverTourHistory>>().setData(list);
    }

    @RequestMapping(value = "/getByPage", method = RequestMethod.GET)
    @ApiOperation(value = "分页获取")
    public Result<IPage<RiverTourHistory>> getByPage(@ModelAttribute RiverTourHistory riverTourHistory,@ModelAttribute PageVo page){

        QueryWrapper<RiverTourHistory> qw = new QueryWrapper<RiverTourHistory>();
        if(riverTourHistory.getPatrolUser() != null && !"".equals(riverTourHistory.getPatrolUser())){
            qw.like("patrol_user",riverTourHistory.getPatrolUser());
        }
        qw.orderByDesc ( "id" );
        IPage<RiverTourHistory> data = iRiverTourHistoryService.page(PageUtil.initMpPage(page),qw);
        return new ResultUtil<IPage<RiverTourHistory>>().setData(data);
    }

    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过id删除")
    public Result<Object> delAllByIds(@PathVariable Long[] ids){

        for(Long id : ids){
            iRiverTourHistoryService.removeById(id);
        }
        return new ResultUtil<Object>().setSuccessMsg("批量通过id删除数据成功");
    }

/*********************************************************************************** 巡河处理 *****************************************************************************************/

    @RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST)
    @ApiOperation(value = "保存或更新数据")
    public Result<RiverTourHistory> saveOrUpdate(@ModelAttribute RiverTourHistory riverTourHistory){
        log.info("接收巡河上报数据："+ riverTourHistory.toString());
        String key = "gps::" + riverTourHistory.getId();
        String getGps = redisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(getGps)){
            getGps = getGps.replace("{", "[");
            getGps = getGps.replace("}", "]");
            getGps = getGps.replace("\"","");
            getGps = getGps.replace("lng:", "");
            getGps = getGps.replace("lat:", "");
            riverTourHistory.setLocus(getGps);
            //删除redis缓存
            Set<String> keysGpsData = redisTemplate.keys(key);
            redisTemplate.delete(keysGpsData);
        }
        if(iRiverTourHistoryService.saveOrUpdate(riverTourHistory)){
            //websocket向客户端推送数据
            myHandler.sendMessageToAllUsers(new TextMessage(""));
            return new ResultUtil<RiverTourHistory>().setData(riverTourHistory);
        }
        return new ResultUtil<RiverTourHistory>().setErrorMsg("操作失败");
    }

    @RequestMapping(value = "/realGps", method = RequestMethod.POST)
    @ApiOperation(value = "接收实时上报坐标")
    public void realGps(@RequestBody String json){

        List<RealGps> list = new ArrayList<>();
        //json数据转实体类经纬度
        RealGps rg = JSON.parseObject(json,RealGps.class);
        //json数据转实体类巡河数据ID
        RealPatrolId rpi = JSON.parseObject(json,RealPatrolId.class);
        String key = "gps::" + rpi.getDataId();

        //取出redis缓存记录
        String getGps = redisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(getGps)){
            list = new Gson().fromJson(getGps, new TypeToken<List<RealGps>>(){}.getType());
        }
        list.add(rg);

        //删除redis缓存
        Set<String> keysGpsData = redisTemplate.keys(key);
        redisTemplate.delete(keysGpsData);
        //在存回去
        redisTemplate.opsForValue().set(key, new GsonBuilder().registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY).create().toJson(list));

    }

    @RequestMapping(value = "/queryRiverHistoryByDate", method = RequestMethod.GET)
    @ApiOperation(value = "批量通过id删除")
    public Result<List<RiverTourHistory>> queryRiverHistoryByDate(@RequestParam Map map){
        List<RiverTourHistory> river = iRiverTourHistoryService.queryRiverHistoryByDateAll(map);
        return new ResultUtil<List<RiverTourHistory>>().setData(river);
    }

    @RequestMapping(value = "/getXcCount", method = RequestMethod.GET)
    @ApiOperation(value = "获取巡河总次数")
    public Result<Object> findAll(){
      Integer count = iRiverTourHistoryService.findTimeAll();
       return new ResultUtil<Object>().setData(count);
    }


    @RequestMapping(value = "/getXhCount", method = RequestMethod.GET)
    @ApiOperation(value = "获取巡河总公里数")
    public Result<Object> findKmAll(){
        String count = iRiverTourHistoryService.findKmAll();
        return new ResultUtil<Object>().setData(count);
    }

    @RequestMapping(value = "/getXcCharts", method = RequestMethod.GET)
    @ApiOperation(value = "获取巡查村统计人数")
    public Result<List<Map>> findXcCharts(){
        //获取集合
        List<Map> count = iRiverTourHistoryService.findXcCharts();
        return new ResultUtil<List<Map>>().setData(count);
    }
}
